import { _ as _export_sfc, z as ref, A as computed, x as useMainStore, y as storeToRefs, U as onShow, B as onLoad, c as createBlock, w as withCtx, ad as login, i as index$g, o as openBlock, b as createVNode, s as index$i, t as createTextVNode, u as toDisplayString, ae as Input, Q as index$x, a3 as showToast, a5 as showLoading, a7 as hideLoading, a1 as navigateTo } from './index-Cc4oxzDN.js';
import { g as getShopInfo } from './market.DCE5Fo51.js';
import { c as createScanPaymentOrder } from './order.D8qtvuIN.js';
import { u as userAuthSession } from './auth.CJjHezpF.js';
import { e as ensurePlatformId } from './platformId.BGlVpsd7.js';
import './platform.EIa5ETLd.js';

const _sfc_main = {
  __name: 'scanpay',
  setup(__props) {

	const title = ref("扫码支付");
	const amount = ref("");
	ref(8);
	const shop = ref();
	const shopId = ref("");

	const payType = ref("weixin");
	computed(() => {
		return {
			width: "80%",
		};
	});
	const paymentable = ref(true);

	const main = useMainStore();
	const {
		member,
		isLogin,
		openid
	} = storeToRefs(main);
	// const onClickLeft = () => {
	// 	uni.navigateBack();
	// }

	const shopName = ref("示例店铺");
	const handlePayment = async () => {
		// 确保平台ID存在
		const hasPlatformId = await ensurePlatformId('payment');
		if (!hasPlatformId) {
			showToast({
				title: '需要授权后才能支付',
				icon: 'none'
			});
			return;
		}
		
		if (!shop.value) {
			console.log("缺少店铺信息");
			// 显示提示消息
			showToast({
				title: "店铺信息不存在",
				icon: "none",
			});
			return;
		}
		// 更具当前输入的金额

		if (amount.value == "" || amount.value == undefined) {
			console.log("请输入正确的金额");
			showToast({
				title: "请输入正确的金额",
				icon: "none",
			});
			return;
		}

		let from = "routine";
		let data = {
			openid: (openid.value !== undefined && openid.value !== null) ? openid.value : '',
			orderType: "scan_payment",
			shopId: shop.value.id,
			payType: payType.value,
			form: from,
			amount: amount.value || 0,
		};
		// 支付请求中
		showLoading({
			title: "支付请求中",
		});

		paymentable.value = false;
		try {
			let result = await createScanPaymentOrder(data);

			console.log(result);
			if (!result) {
				hideLoading();
				return;
			}

			// 页面跳转到结算页
			if (result.code === 0 && result.data && result.data.orderId) {
				navigateTo({
					url: `/pages/order/checkout?orderId=${result.data.orderId}`
				});
			}
		} catch (error) {
			console.error(error);
		}
		// this.$router.push("/pages/components/pages/scanpay/pay_success");
	};

	const wechatMiniLogin = () => {
		//this.$u.toast('登录中');
		login({
			provider: 'weixin'
		}).then(async (res) => {
			let data = await userAuthSession({
				code: res.code
			});
			if (data) {
				main.SET_OPENID(data.openId);
				console.log('openid', data.openId);

				if (data.hasOwnProperty('userInfo') && data.accessToken && data.accessToken != '') {
					main.SET_MEMBER(data.userInfo);
					main.SET_TOKEN(data.accessToken);
					console.log("data.accesses:", data.accesses);
					main.SET_ACCESSES(data.accesses);
				}
			}
		});
	};

	onShow(() => {
		console.log("init");

		if (!openid.value) {
			wechatMiniLogin();
		}

		if (shopId.value) {
			console.log("shopId =>>", shopId.value);
			loadShopInfo(shopId.value).then((result) => {
				console.log(result);
			});
		}
		paymentable.value = true;
		console.log(paymentable.value);


	});



	onLoad((options) => {
		//没从当前url 获取 参数 shopId 的值
		// 通过uni.getStorageSync('shopId') 获取

		console.log("options=>>>>", options);

		// 扫码截取参数
		if (options.q !== undefined) {
			let q = decodeURIComponent(options.q);
			// q 是解码后的完整url
			console.log("q", q); // 打印出完整的二维码内容

			// 如果需要获取特定的参数，可以使用正则表达式或者分割字符串的方法
			// 例如，获取名为 'combo_code' 的参数
			let comboCodeParams = q.split("shopId=")[1].split("&")[0];
			console.log(comboCodeParams); // 打印出 'combo_code' 参数的值
			shopId.value = comboCodeParams;
		}

		paymentable.value = true;
		console.log(paymentable.value);
	});

	const loadShopInfo = async (shopId) => {
		// 后台检查 shopId 是否存在
		const shopInfo = await getShopInfo({
			shopId: shopId,
		});
		if (shopInfo) {
			console.log(shopInfo);
		} else {
			console.log("load shop info fail");
		}
		if (shopInfo) {
			shop.value = shopInfo;
			title.value = shopInfo.name;
			shopName.value = shopInfo.name || "示例店铺";
		} else {
			console.log("店铺信息不存在");
			shop.value = null;
		}

		return "success";
	};

return (_ctx, _cache) => {
  const _component_v_uni_text = index$i;
  const _component_v_uni_view = index$g;
  const _component_v_uni_input = Input;
  const _component_v_uni_button = index$x;

  return (openBlock(), createBlock(_component_v_uni_view, { class: "container" }, {
    default: withCtx(() => [
      createVNode(_component_v_uni_view, { class: "payment-form" }, {
        default: withCtx(() => [
          createVNode(_component_v_uni_view, { class: "header" }, {
            default: withCtx(() => [
              createVNode(_component_v_uni_text, { class: "shop-name" }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(shopName.value), 1)
                ]),
                _: 1
              })
            ]),
            _: 1
          }),
          createVNode(_component_v_uni_view, { class: "form-item" }, {
            default: withCtx(() => [
              createVNode(_component_v_uni_text, { class: "label" }, {
                default: withCtx(() => [
                  createTextVNode("付款金额")
                ]),
                _: 1
              }),
              createVNode(_component_v_uni_input, {
                type: "digit",
                modelValue: amount.value,
                "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => ((amount).value = $event)),
                class: "input",
                placeholder: "请输入付款金额"
              }, null, 8, ["modelValue"])
            ]),
            _: 1
          }),
          createVNode(_component_v_uni_button, {
            onClick: _cache[1] || (_cache[1] = $event => (handlePayment())),
            class: "payment-button",
            disabled: !paymentable.value
          }, {
            default: withCtx(() => [
              createTextVNode(" 立即支付 ")
            ]),
            _: 1
          }, 8, ["disabled"])
        ]),
        _: 1
      })
    ]),
    _: 1
  }))
}
}

};
const scanpay = /*#__PURE__*/_export_sfc(_sfc_main, [['__scopeId',"data-v-a218c221"]]);

export { scanpay as default };
